// @Author EthanScriptOn
// @Desc
package mysql_operator

import (
	"fmt"
	"gitee.com/fatzeng/srf_switch_basic_components/common/identity"
	"gitee.com/fatzeng/srf_switch_expansion_package/extend_config"
	"gitee.com/fatzeng/srf_switch_expansion_package/extend_param_collector"
	"gitee.com/fatzeng/srf_switch_stream_bridge/framework/actuator"
	"gitee.com/fatzeng/srf_switch_stream_bridge/framework/operator"
	"os"
)

type LocalWriteOperator struct {
	*identity.IdentityInformationCarrier
}

func (l *LocalWriteOperator) Execute(ctx *actuator.SrfSwitchBridgeActuatorContext, configIdentifier interface{}, structureParam interface{}) (interface{}, error) {
	config := operator.GetOperatorConfig(configIdentifier)
	if config == nil {
		return nil, fmt.Errorf("config is nil")
	}
	operatorConfig, ok := config.(*extend_config.LocalWriteOperatorConfig)
	if !ok {
		return nil, fmt.Errorf("config is not LocalWriteOperatorConfig")
	}
	if !operatorConfig.IsValid() {
		return nil, fmt.Errorf("LocalWriteOperatorConfig is not valid")
	}
	if structureParam == nil {
		return nil, fmt.Errorf("structureParam is nil")
	}
	params, ok := structureParam.(*extend_param_collector.LocalParams)
	if !params.IsValid() {
		return nil, fmt.Errorf("LocalParams is not valid")
	}
	file, err := createFile(operatorConfig)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	responses := make([]*extend_config.LocalWriteOperatorResponse, 0)
	for _, content := range params.Content {
		_, err = file.WriteString(content + "\n")
		resp := new(extend_config.LocalWriteOperatorResponse)
		resp.FilePath = operatorConfig.FilePath
		resp.OriginMsg = content
		resp.Err = err
		responses = append(responses, resp)
	}
	return responses, nil
}

func createFile(config *extend_config.LocalWriteOperatorConfig) (file *os.File, err error) {
	flag := 0
	if config.IsAppend {
		flag = os.O_APPEND | os.O_CREATE | os.O_WRONLY
	} else {
		flag = os.O_CREATE | os.O_WRONLY
	}
	file, err = os.OpenFile(config.FilePath, flag, 0644)
	if err != nil {
		return nil, fmt.Errorf("failed to open file: %v", err)
	}
	return file, nil
}
